package com.itserver.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {

    private static final String signKey = "itheima".repeat(6);
    // 使用配置文件中的过期时间
    private static  Long expire ;
    private static final SecretKey key = Keys.hmacShaKeyFor(signKey.getBytes());
    private static final SecretKey secretKey = Jwts.SIG.HS256.key().build();

    @Autowired
    public JwtUtils(Config config) {
        expire = config.getExpire() * 60 * 1000L;
    }
    /**
     * 生成JWT令牌
     */
    public static String generateJwt(Map<String,Object> claims){
        // 生成uuid
        claims.put("uuid",java.util.UUID.randomUUID().toString());

        Date expireDate = new Date(System.currentTimeMillis() + expire);
        return  Jwts.builder().signWith(key).claims(claims).expiration(expireDate).compact();
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static Claims parseJWT(String jwt){
        try {
            return Jwts.parser().verifyWith(key).build().parseSignedClaims(jwt).getPayload();
            //OK, we can trust this JWT
        } catch (JwtException e) {
            //don't trust the JWT!
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String,Object> claims = Map.of("id",1,"username","admin");
        String token = generateJwt(claims);
        System.out.println(token);
        System.out.println(parseJWT(token));
    }
}
